package com.xinqi.common.third.sms.help;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.http.MethodType;

import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.base.utils.chars.Patterns;
import com.xinqi.common.base.utils.json.JSON;
import com.xinqi.common.core.utils.JsonUtils;
import com.xinqi.common.core.utils.MessageUtils;
import com.xinqi.common.third.sms.SmsProperties;
import com.xinqi.common.third.sms.entity.SmsResult;
import com.xinqi.common.third.sms.exception.SmsException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;

/**
 * 阿里云短信发送类
 *
 * @author linkai
 * @date 2023/2/21
 */
@Slf4j
@RequiredArgsConstructor
public class SmsHelp {
    private final SmsProperties smsProperties;
    private final Client client;

    public SmsHelp(SmsProperties smsProperties) throws Exception {
        this.smsProperties = smsProperties;
        Config config = new Config()
            // 您的AccessKey ID
            .setAccessKeyId(smsProperties.getAccessKeyId())
            // 您的AccessKey Secret
            .setAccessKeySecret(smsProperties.getAccessKeySecret())
            // 访问的域名
            .setEndpoint(smsProperties.getEndpoint());
        this.client = new Client(config);
    }

    public SmsResult send(String phone, Map<String, Object> param, String templateId) {
        if (StringUtils.isBlank(phone)) {
            throw new SmsException("手机号不能为空");
        }
        if (StringUtils.isBlank(templateId)) {
            throw new SmsException("模板ID不能为空");
        }
        SendSmsRequest req = new SendSmsRequest()
            .setPhoneNumbers(phone)
            .setSignName(smsProperties.getSignName())
            .setTemplateCode(templateId)
            .setTemplateParam(JsonUtils.toJsonString(param));
        try {
            SendSmsResponse resp = client.sendSms(req);
            if (Objects.equals("OK", resp.getBody().getCode())) {
                return SmsResult.builder().isSuccess(true)
                    .message(MessageUtils.message("sms.code.get.is.success"))
                    .response(JsonUtils.toJsonString(resp))
                    .build();
            } else {
                return SmsResult.builder().isSuccess(false)
                    .message(resp.getBody().getMessage())
                    .response(JsonUtils.toJsonString(resp))
                    .build();
            }
        } catch (Exception e) {
            throw new SmsException(e.getMessage());
        }
    }
}
